// 退款/售后 模拟API接口
// 注意：这是前端模拟接口，实际使用时需要对接真实后端API

import request from '@/utils/requestUtil'

// 模拟数据存储（实际应该存储在localStorage或vuex中）
let refundList = [];
let refundIdCounter = 1;

/**
 * 申请退款
 * @param {Object} data - 退款申请数据
 * @param {Number} data.orderId - 订单ID
 * @param {String} data.reason - 退款原因
 * @param {String} data.description - 详细描述（可选）
 */
export function applyRefund(data) {
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			// 模拟创建退款单
			const refundId = refundIdCounter++;
			const refundOrder = {
				id: refundId,
				refundSn: `RF${Date.now()}${refundId}`, // 退款单号
				orderId: data.orderId,
				orderSn: data.orderSn || `ORD${data.orderId}`,
				productName: data.productName || '商品名称',
				productPic: data.productPic || '/static/missing-face.png',
				refundAmount: data.refundAmount || 0,
				reason: data.reason,
				description: data.description || '',
				status: 0, // 0-申请中, 1-审核通过, 2-退款成功, 3-已拒绝, 4-已取消
				createTime: new Date().getTime(),
				handleTime: null,
				successTime: null,
				timeline: [
					{
						status: '提交退款申请',
						time: new Date().getTime(),
						description: `退款原因：${data.reason}`
					}
				]
			};

			// 保存到模拟存储
			refundList.unshift(refundOrder);

			// 存储到localStorage
			try {
				uni.setStorageSync('refundList', JSON.stringify(refundList));
			} catch (e) {
				console.error('保存退款列表失败', e);
			}

			resolve({
				code: 200,
				message: '申请退款成功',
				data: refundOrder
			});
		}, 500);
	});
}

/**
 * 获取退款订单列表
 * @param {Object} params - 查询参数
 * @param {Number} params.status - 退款状态 (-1:全部, 0:申请中, 1:审核通过, 2:退款成功, 3:已拒绝, 4:已取消)
 * @param {Number} params.pageNum - 页码
 * @param {Number} params.pageSize - 每页数量
 */
export function fetchRefundList(params) {
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			// 从localStorage加载数据
			try {
				const storedData = uni.getStorageSync('refundList');
				if (storedData) {
					refundList = JSON.parse(storedData);
				}
			} catch (e) {
				console.error('加载退款列表失败', e);
			}

			// 筛选数据
			let filteredList = refundList;
			if (params.status !== -1 && params.status !== undefined) {
				filteredList = refundList.filter(item => item.status === params.status);
			}

			// 分页
			const pageNum = params.pageNum || 1;
			const pageSize = params.pageSize || 10;
			const start = (pageNum - 1) * pageSize;
			const end = start + pageSize;
			const pageData = filteredList.slice(start, end);

			resolve({
				code: 200,
				message: '获取成功',
				data: {
					list: pageData,
					total: filteredList.length,
					pageNum: pageNum,
					pageSize: pageSize
				}
			});
		}, 300);
	});
}

/**
 * 获取退款详情
 * @param {Number} refundId - 退款ID
 */
export function fetchRefundDetail(refundId) {
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			// 从localStorage加载数据
			try {
				const storedData = uni.getStorageSync('refundList');
				if (storedData) {
					refundList = JSON.parse(storedData);
				}
			} catch (e) {
				console.error('加载退款列表失败', e);
			}

			const refund = refundList.find(item => item.id === refundId);

			if (refund) {
				resolve({
					code: 200,
					message: '获取成功',
					data: refund
				});
			} else {
				reject({
					code: 404,
					message: '退款单不存在'
				});
			}
		}, 300);
	});
}

/**
 * 取消退款申请
 * @param {Number} refundId - 退款ID
 */
export function cancelRefund(refundId) {
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			// 从localStorage加载数据
			try {
				const storedData = uni.getStorageSync('refundList');
				if (storedData) {
					refundList = JSON.parse(storedData);
				}
			} catch (e) {
				console.error('加载退款列表失败', e);
			}

			const refund = refundList.find(item => item.id === refundId);

			if (refund) {
				if (refund.status !== 0) {
					reject({
						code: 400,
						message: '当前状态不允许取消'
					});
					return;
				}

				refund.status = 4; // 已取消
				refund.handleTime = new Date().getTime();
				refund.timeline.push({
					status: '取消退款申请',
					time: new Date().getTime(),
					description: '用户主动取消退款申请'
				});

				// 保存到localStorage
				try {
					uni.setStorageSync('refundList', JSON.stringify(refundList));
				} catch (e) {
					console.error('保存退款列表失败', e);
				}

				resolve({
					code: 200,
					message: '取消成功',
					data: refund
				});
			} else {
				reject({
					code: 404,
					message: '退款单不存在'
				});
			}
		}, 300);
	});
}

/**
 * 模拟商家审核通过（仅用于测试）
 */
export function mockApproveRefund(refundId) {
	return new Promise((resolve) => {
		setTimeout(() => {
			try {
				const storedData = uni.getStorageSync('refundList');
				if (storedData) {
					refundList = JSON.parse(storedData);
				}
			} catch (e) {
				console.error('加载退款列表失败', e);
			}

			const refund = refundList.find(item => item.id === refundId);
			if (refund && refund.status === 0) {
				refund.status = 1;
				refund.handleTime = new Date().getTime();
				refund.timeline.push({
					status: '商家审核通过',
					time: new Date().getTime(),
					description: '商家已同意退款申请，退款处理中'
				});

				// 继续模拟退款成功
				setTimeout(() => {
					refund.status = 2;
					refund.successTime = new Date().getTime();
					refund.timeline.push({
						status: '退款成功',
						time: new Date().getTime(),
						description: `退款金额￥${refund.refundAmount}已原路退回`
					});

					try {
						uni.setStorageSync('refundList', JSON.stringify(refundList));
					} catch (e) {
						console.error('保存退款列表失败', e);
					}
				}, 2000);

				try {
					uni.setStorageSync('refundList', JSON.stringify(refundList));
				} catch (e) {
					console.error('保存退款列表失败', e);
				}
			}

			resolve({
				code: 200,
				message: '操作成功'
			});
		}, 300);
	});
}
